package servlet;

import util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.sql.*;

/**
 * @author MissChen
 * @date 2024年04月23日 16:42
 */
@WebServlet("*.emp")
public class EmpServlet2 extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String path = request.getServletPath();
        switch (path) {
            case "/showAddEmp.emp":
                showAddEmp(request, response);
                break;
            case "/addEmp.emp":
                addEmp(request, response);
                break;
            case "/findAll.emp":
                findAll(request, response);
                break;
            case "/showModifyEmp.emp":
                showModifyEmp(request, response);
                break;
            case "/modifyEmp.emp":
                modifyEmp(request, response);
                break;
            case "/deleteEmp.emp":
                deleteEmp(request, response);

        }
    }

    public void showAddEmp(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter out = response.getWriter();
        out.print("<!DOCTYPE html>");
        out.print("<html lang='en'>");
        out.print("<head>");
        out.print("<meta charset='UTF-8'>");
        out.print("<title>添加员工</title>");
        out.print("</head>");
        out.print("<body>");
        out.print("<h1>添加员工信息</h1>");
        out.print("<a href='findAll.emp'>返回员工列表</a>");
        out.print("<hr>");
        out.print("<form action='addEmp.emp' method='post'>");
        out.print("    姓名:<input type='text' name='name'><br>");
        out.print("    工资:<input type='text' name='salary'><br>");
        out.print("    性别:");
        out.print("    <input type='radio' name='gender' value='man'>男");
        out.print("    <input type='radio' name='gender' value='woman'>女");
        out.print("    <br>");
        out.print("    学历:");
        out.print("    <select name='edu' >");
        out.print("        <option value='-1'>请选择</option>");
        out.print("        <option value='1'>高中</option>");
        out.print("        <option value='2'>大专</option>");
        out.print("        <option value='3'>本科</option>");
        out.print("        <option value='4'>研究生</option>");
        out.print("    </select>");
        out.print("    <br>");
        out.print("    兴趣:");
        out.print("    <input type='checkbox' name='hobbies' value='eat'>吃饭");
        out.print("    <input type='checkbox' name='hobbies' value='sleep'>睡觉");
        out.print("    <input type='checkbox' name='hobbies' value='beat'>打豆豆");
        out.print("    <input type='submit'  value='提交'>");
        out.print(" </form>");
        out.print("</body>");
        out.print("</html>");

    }

    public void addEmp(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        request.setCharacterEncoding("UTF-8");
        String name = request.getParameter("name");
        String salary = request.getParameter("salary");
        String gender = request.getParameter("gender");
        String edu = request.getParameter("edu");
        // request.getParameterValues()用于获取服务器值为数组的场景，一般用于复选框
        String[] hobbies = request.getParameterValues("hobbies");

        // 1.根据页面创建对应的t_emp
        // 2.根据页面获取的数据执行JDBC的添加操作

        Connection conn = null;
        PreparedStatement ps = null;
        String url = "jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url, "root", "root");

            String sql = new StringBuffer()
                    .append(" insert into ")
                    .append(" t_emp ")
                    .append(" (name,salary,gender,edu,hobbies) ")
                    .append(" values ")
                    .append(" (?,?,?,?,?) ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setString(1, name);
            ps.setDouble(2, Double.parseDouble(salary));
            ps.setString(3, gender);
            ps.setString(4, edu);
            ps.setString(5, StringUtil.arrayToString(hobbies));
            //执行DML操作
            ps.executeUpdate();

            response.sendRedirect("findAll.emp");

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            out.println("<h1 style='color:red;'>对不起，添加失败</h1>");
        } catch (SQLException e) {
            e.printStackTrace();
            out.println("<h1 style='color:red;'>对不起，添加失败</h1>");
        } catch (IOException e) {
            e.printStackTrace();
            out.println("<h1 style='color:red;'>对不起，数据库访问异常</h1>");
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

        }


    }

    public void findAll(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE html>");
        out.println("<html lang='en'>");
        out.println(" <head>");
        out.println(" <meta charset='UTF-8'>");
        out.println(" <title>员工列表</title>");
        out.println(" </head>");
        out.println(" <body>");
        out.println("      <h1>员工列表</h1>");
        out.println("     <table>");
        out.println("         <thead>");
        out.println("            <td>编号</td>");
        out.println("            <td>姓名</td>");
        out.println("            <td>工资</td>");
        out.println("            <td>操作</td>");
        out.println("       </thead>");
        out.println("      <tbody>");
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String url = "jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url, "root", "root");
            String sql = new StringBuffer()
                    .append(" select id,name,salary,gender,edu,hobbies ")
                    .append(" from t_emp ")
                    .toString();
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            while (rs.next()) {
                out.println("          <tr>");
                out.println("             <td>" + rs.getInt("id") + "</td>");
                out.println("              <td>" + rs.getString("name") + "</td>");
                out.println("              <td>" + rs.getDouble("salary") + "</td>");
                out.println("               <td>");

                out.println("                   <a href='showModifyEmp?id=" + rs.getInt("id") + "'>修改</a>");
                out.println("                 <a href='deleteEmp?id=" + rs.getInt("id") + "'>删除</a>");
                out.println("               </td>");
                out.println("           </tr>");
            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();

        } catch (SQLException e) {
            e.printStackTrace();

        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }


        out.println("       </tbody>");
        out.println("   </table>");
        out.println("</body>");
        out.println("</html>");
    }

    public void showModifyEmp(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter("id");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String url = "jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url, "root", "root");
            String sql = new StringBuffer()
                    .append(" select id,name,salary,gender,edu,hobbies ")
                    .append(" from t_emp ")
                    .append(" where id=? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setInt(1, Integer.parseInt(id));
            rs = ps.executeQuery();
            if (rs.next()) {

                out.println("<!DOCTYPE html>");
                out.println("<html lang='en'>");
                out.println("    <head>");
                out.println("         <meta charset='UTF-8'>");
                out.println("        <title>修改员工信息</title>");
                out.println("    </head>");
                out.println("    <body>");
                out.println("        <h1>修改员工信息</h1>");
                out.println("        <a href='findAll.emp'>返回员工列表</a>");
                out.println("        <hr>");
                out.println("        <form action='modifyEmp.emp' method='post'>");
                out.println("       编号:<input type='text' name='id' readonly  value='" + rs.getInt("id") + "'><br>");
                out.println("       姓名:<input type='text' name='name' value='" + rs.getString("name") + "'><br>");
                out.println("            工资:<input type='text' name='salary' value=" + rs.getDouble("salary") + "><br>");
                out.println("            性别:");
                out.println("            <input type='radio' name='gender' value='man'" + (rs.getString("gender").equals("man") ? "checked" : "") + ">男");
                out.println("            <input type='radio' name='gender' value='woman'" + (rs.getString("gender").equals("woman") ? "checked" : "") + ">女");
                out.println("            <br>");
                out.println("            学历:");
                out.println("            <select name='edu'>");
                out.println("               <option value='-1'>请选择</option>");
                out.println("               <option value='1'" + (rs.getString("edu").equals("1") ? "selected" : "") + ">高中</option>");
                out.println("               <option value='2'" + (rs.getString("edu").equals("2") ? "selected" : "") + ">大专</option>");
                out.println("               <option value='3'" + (rs.getString("edu").equals("3") ? "selected" : "") + ">本科</option>");
                out.println("               <option value='4'" + (rs.getString("edu").equals("4") ? "selected" : "") + ">研究生</option>");
                out.println("           </select>");
                out.println("           <br>");
                out.println("           兴趣:");
                out.println("           <input type='checkbox' name='hobbies' value='eat'" + StringUtil.checkHobby(rs.getString("hobbies"), "eat") + ">吃饭");

                out.println("           <input type='checkbox' name='hobbies' value='sleep'" + StringUtil.checkHobby(rs.getString("hobbies"), "sleep") + ">睡觉");
                out.println("           <input type='checkbox' name='hobbies' value='beat'" + StringUtil.checkHobby(rs.getString("hobbies"), "beat") + ">打豆豆");
                out.println("           <input type='submit'  value='提交'>");
                out.println("        </form>");
                out.println("    </body>");
                out.println("</html>");
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();

        } catch (SQLException e) {
            e.printStackTrace();

        }
    }


    public void modifyEmp(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        request.setCharacterEncoding("utf-8");
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        String salary = request.getParameter("salary");
        String gender = request.getParameter("gender");
        String edu = request.getParameter("edu");
        String[] hobbies = request.getParameterValues("hobbies");
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String url = "jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url, "root", "root");
            String sql = new StringBuffer()
                    .append(" update t_emp ")
                    .append(" set ")
                    .append(" name=?,salary=?,gender=?,edu=?,hobbies=?  ")
                    .append(" where id=? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setString(1, name);
            ps.setDouble(2, Double.parseDouble(salary));
            ps.setString(3, gender);
            ps.setString(4, edu);
            ps.setString(5, StringUtil.arrayToString(hobbies));
            ps.setInt(6, Integer.parseInt(id));
            ps.executeUpdate();
            response.sendRedirect("findAll.emp");

        } catch (ClassNotFoundException e) {
            e.printStackTrace();

        } catch (SQLException e) {
            e.printStackTrace();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    public void deleteEmp(HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("id");
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String url = "jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url, "root", "root");
            String sql = new StringBuffer()
                    .append(" delete from t_emp ")
                    .append(" where id=? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setInt(1, Integer.parseInt(id));
            ps.executeUpdate();
            response.sendRedirect("findAll.emp");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();

        } catch (SQLException e) {
            e.printStackTrace();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

    }

}
